﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using wrzy.utll;
using System.IO;
using System.Data.OracleClient;
using System.Threading;
using System.Data.SqlClient;

namespace wrzy
{
    public partial class Form1 : Form
    {

        string nowTime;//当前的时间
        FileStream currentLog;
        String lsql;
        int mIntPackCnt;
        String mStrCollieryID, mStrTransUnitID, mStrCoalKindID, mStrPotCode;   //煤矿ID,车队ID,煤种ID,罐号
        bool errState = false, runState = false, isRun = false;
        public String mStrCurStep, mStrProcStatus;                //当前执行所处步骤
        zyDriver zyDriver;
        OracleDataReader reader;
        Boolean mStrTPStatus, mStrPkgStatus;  //托盘容器准备就绪,封装系统准备就绪
        oracleDatabase oracle;
        tp tp;
        string mStrZyStatus;//制样状态表
        fzj fzj;

        DateTime mIntStartTime = new DateTime();
        String mStrSamCode, mstrBarCode;        //待处理制样的采样编码,扫描到的制样条码
        public Form1()
        {
            InitializeComponent();
        }
        public void writeMakeRunLog(string SamCode, string number, string text)
        {

            string date = General.getDate();
            string time = General.getTime();
            string lsql = "insert into T_MakeRUNLOG (logdate,logtime,samcode,handletype,logtext) values ('" + date + "','" + time + "','" + SamCode + "','" + number + "','" + text + "')";
            oracle.ExecuteSql(lsql);
            this.t_MAKERUNLOGTableAdapter.FillBy1(this.makelog.T_MAKERUNLOG);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“makelog.T_MAKERUNLOG”中。您可以根据需要移动或移除它。
          
            mStrZyStatus = "zyStatus";
            mStrProcStatus = "zyprocStatus";
            mStrSamCode = "";    //待处理的采样编码
            tmr_queryCode.Enabled = true;
            oracle = new oracleDatabase();
            zyDriver = new zyDriver();
            fzj = new fzj();
            this.tp = new tp();
            this.t_MAKERUNLOGTableAdapter.FillBy1(this.makelog.T_MAKERUNLOG);
            
        }



        /// <summary>
        /// 查看是否有采样的错误
        /// </summary>
        /// <param name="samcode">当前制样的采样码</param>
        /// <returns>如果没有错误返回false,否则返回True</returns>
        public Boolean CyCw(string samcode)
        {
            oracleDatabase data = new oracleDatabase();
            int ErrorNumber = data.GetRecordCount(@"select * from t_Makerunlog where samcode='" + samcode + "' and handletype in ('2','3')");
            if (ErrorNumber == 0)
                return false;
            else
                return true;
        }
        /// <summary>
        /// 查看是否有系统错误
        /// </summary>
        public Boolean SysErr()
        {
            sqlServer data = new sqlServer();
            SqlDataReader reader = data.ExecuteReader("select stalog from zyprocStatus");
            String ErrStr;
            reader.Read();
            ErrStr = reader.GetValue(0).ToString();
            reader.Close();
            if (ErrStr.Equals("") || ErrStr.Equals("0"))
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        private void tmr_startMake_Tick(object sender, EventArgs e)
        {

            string isql = "", lSamSql = "", ldate, ltime;

            lsql = "select * from t_Makerunlog where samcode='" + mStrSamCode + "'and handletype in ('2','3')";
            if (oracle.GetRecordCount(lsql) > 0)
            {
                MessageBox.Show("处理错误信息");
                return;
            }
            ltime = General.getTime();
            ldate = General.getDate();
            lsql = "update t_makerunlog set handletype='1' where " +
                "logdate>=to_char(to_date('" + ldate + "','yyyy-mm-dd')-2,'yyyy-mm-dd')and logdate<='" + ldate + "'";
            oracle.ExecuteSql(lsql);
            if (!zyDriver.zyready())
            {
                return;
            }
            mStrCurStep = "tmr_StartMake";
            mIntPackCnt = 1;
            writeMakeRunLog(mStrSamCode, "0", "制样启动，采样编码:" + mStrSamCode);

            // MessageBox.Show("启动制样");
            //对应桶号
            lsql = @"select senddate,potcode,collieryid,transunitid,coalkindid,   " +
   "      (select count(id) from t_truckenter where samcode=cd.samcode) samCount    " +
   "from t_coalsamcode cd  " +
   "where samcode='" + mStrSamCode + "'";
            oracle = new oracleDatabase();
            sqlServer sql = new sqlServer();


            if (oracle.GetRecordCount(lsql) > 0)
            {

                reader = oracle.ExecuteReader(lsql);
                reader.Read();

                Edit_ClearDate.Text = reader.GetValue(0).ToString();//制样的时间
                Edit_SamNum.Text = reader.GetValue(5).ToString();//采样的总数


                mStrCollieryID = reader.GetValue(2).ToString();
                mStrTransUnitID = reader.GetValue(3).ToString();
                mStrCoalKindID = reader.GetValue(4).ToString();
                mStrPotCode = reader.GetValue(1).ToString();

            }
            //判断采样机在哪个采样
            lSamSql = "";
            lsql = "select samaddr,count(id) from t_truckenter" +
         " where samcode='" + mStrSamCode + "' group by samaddr having count(id)>0";

            if (oracle.GetRecordCount(lsql) > 0)
            {
                try
                {
                    reader = oracle.ExecuteReader(lsql);

                    while (reader.Read())
                    {
                        if (reader.GetString(0).Equals("房间1"))
                        {
                            if (lSamSql.Trim().Equals(""))
                            {
                                lSamSql = "firsam=1,Firbarrel=" + mStrPotCode;
                            }
                            else
                            {
                                lSamSql = lSamSql + ",firsam=1,Firbarrel=" + mStrPotCode;
                            }
                        }
                        else if (reader.GetString(0).Equals("房间2"))
                        {
                            //MessageBox.Show("房间2");
                            if (lSamSql.Trim().Equals(""))
                            {
                                lSamSql = "secsam=1,secbarrel=" + mStrPotCode;
                            }

                            else
                            {
                                lSamSql = lSamSql + ",secsam=1,secbarrel=" + mStrPotCode;
                            }
                        }
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    if (reader.IsClosed)
                    {
                        reader.Close();
                    }
                }
            }
            //如果当前的采样编码没有在任何一个采样中采过
            if (lSamSql.Equals(""))
            {
                try
                {
                    lsql = @"update t_dict set value=null where name='制样用采样编码' and parentid=(select id from t_dict where name='系统参数')";
                    oracle.ExecuteSql(lsql);
                    lsql = @"update t_coalsamcode set maked='1' where samcode='" + mStrSamCode + "'";
                    oracle.ExecuteSql(lsql);
                    writeMakeRunLog(mStrSamCode, "0", "当前采样编码" + mstrBarCode + "没有采样数据");
                    MessageBox.Show("没有采样数据");
                    mStrSamCode = "";
                }
                catch (Exception e2)
                {
                    writeMakeRunLog(mStrSamCode, "2", "更新采样编码信息出错");
                    tmr_startMake.Enabled = false;
                    return;
                }
                finally
                {
                    lsql = "update " + mStrZyStatus + " set start=0,stop=0,firsam=0,secsam=0,Firbarrel=0,secbarrel=0,Firdrop=0,secdrop=0";
                    sql.ExecuteSql(lsql);
                }
                tmr_startMake.Enabled = false;
                tmr_queryCode.Enabled = true;
            }
            try
            {
                lsql = "update zyStatus set " + lSamSql;
                sql.ExecuteSql(lsql);
                writeMakeRunLog(mStrSamCode, "0", "启动制样机");
                zyDriver.zyStart();
                //MessageBox.Show("启动制样");
            }
            catch (Exception e2)
            {
                writeMakeRunLog(mStrSamCode, "0", "启动制样机出错");
                mStrTPStatus = false;
                mStrPkgStatus = false;
                tmr_startMake.Enabled = false;
                return;
            }
            mStrTPStatus = false;
            mStrPkgStatus = false;
            tmr_startMake.Enabled = false;
            tmr_TPTimer.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            tmr_startMake.Enabled = false;
            tmr_TPTimer.Enabled = false;
            tmr_PackageTimer.Enabled = false;
            tmr_tpfin.Enabled = false;
            tmr_BarCode.Enabled = false;
            tmr_PackFinish.Enabled = false;
            tmr_makeFinish.Enabled = false;
            tmr_queryCode.Enabled = true;
        }
        private void edit_barCode1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                edit_barCode2.Focus();
            }
        }

        private void tmr_makeFinish_Tick(object sender, EventArgs e)
        {
            string lsql, lerror;
            DateTime dt, dt2;
            oracleDatabase oracle = new oracleDatabase();
            sqlServer sql = new sqlServer();
            mStrCurStep = "tmr_makeFinish";


            if (SysErr())
            {
                MessageBox.Show("系统故障");
                tmr_tpfin.Enabled = false;
                return;
            }
            if (!zyDriver.zyFin())
            {
                return;
            }
            try
            {
                zyDriver.zyStop();
                lsql = "update " + mStrZyStatus + " set stop=0,firsam=0,firbarrel=0,secsam=0,secbarrel=0";
                sql.ExecuteSql(lsql);

            }
            catch (Exception e3)
            {
                writeMakeRunLog(mStrSamCode, "2", "置系统停止信号出错");
                tmr_makeFinish.Enabled = false;
                return;
            }
            try
            {
                lsql = "update t_dict set value=null where name='制样用采样编码' and parentid=(select id from t_dict where name='系统参数')";
                oracle.ExecuteSql(lsql);
                writeMakeRunLog(mStrSamCode, "0", "制样完毕,系统已停止");
                mStrSamCode = "";
            }
            catch (Exception e2)
            {
                writeMakeRunLog(mStrSamCode, "2", "更新采样编码信息出错");
                tmr_makeFinish.Enabled = false;
                return;
            }
            edit_SamCode.Text = "";
            Edit_ClearDate.Text = "";
            Edit_SamNum.Text = "";
            tmr_makeFinish.Enabled = false;
            //tmr_QueryCode.Enabled = true;
        }

        private void tmr_queryCode_Tick(object sender, EventArgs e)
        {
            string lsql, ldate, ltime, lSamSql;
            lsql = "select value from t_dict where name='制样用采样编码' and parentid=(select id from t_dict where name='系统参数')";
            OracleDataReader myReader;
            myReader = oracle.ExecuteReader(lsql);
            myReader.Read();
            if (myReader.GetValue(0).ToString().Equals(""))
            {
                return;
            }
            else
            {
                mStrSamCode = myReader.GetValue(0).ToString().Trim();
                //待处理的采样编码

            }
            if (mStrSamCode.Equals(""))
                return;
            edit_SamCode.Text = mStrSamCode;
            // MessageBox.Show("已找到采样编码，延时半分钟");
            tmr_queryCode.Enabled = false;
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(500);
            }
            tmr_startMake.Enabled = true;
        }

        private void tmr_TPTimer_Tick(object sender, EventArgs e)
        {
            mStrCurStep = "tmr_TP";
            //  MessageBox.Show("检查托盘是否准备好");
            if (SysErr() == true)
            {
                MessageBox.Show("托盘有错误");
                tmr_TPTimer.Enabled = false;
                return;
            }
            if (tp.TpStatus() == true)
            {
                mStrTPStatus = true;
                writeMakeRunLog(mStrSamCode, "0", "托盘系统准备好");
                tmr_TPTimer.Enabled = false;
                tmr_PackageTimer.Enabled = true;
            }
        }

        private void tmr_tpfin_Tick(object sender, EventArgs e)
        {
            string lerror, lsql;
            mStrCurStep = "tmr_tpFin";
            Boolean lTpFin;
            DateTime dt1 = new DateTime();
            DateTime dt2 = new DateTime();
            TimeSpan ts;
            dt1 = DateTime.Now;
            if (mIntPackCnt == 1)
            {
                lTpFin = tp.FirstFin();

            }
            else
            {
                lTpFin = tp.SecpFin();
            }
            if (SysErr())
            {
                MessageBox.Show("系统故障");
                tmr_tpfin.Enabled = false;
                return;
            }
            if (!lTpFin)
            {
                dt2 = DateTime.Now;
                ts = dt2 - mIntStartTime;
                if (ts.TotalMinutes > 5)
                {
                    writeMakeRunLog(mStrSamCode, "2", "5分钟仍然未给料完毕");

                    tmr_tpfin.Enabled = false;
                    return;
                }
            }
            else
            {
                MessageBox.Show("给料完成");
                mIntStartTime = DateTime.Now;
                tmr_tpfin.Enabled = false;
                tmr_BarCode.Enabled = false;
                tmr_BarCode.Enabled = true;
            }
        }

        private void tmr_PackageTimer_Tick(object sender, EventArgs e)
        {


            string lsql;
            mStrCurStep = "tmr_Package";
            sqlServer sql = new sqlServer();
            if (!mStrTPStatus)
            {
                return;
            }
            if (fzj.fzjStatus() == true) //如果封装机没有准备好就退出
            {
                return;
            }
            writeMakeRunLog(mStrSamCode, "0", "封装系统准备好");
            try
            {
                if (mIntPackCnt == 1)
                {
                    lsql = "update " + mStrZyStatus + " set firdrop=1";
                    sql.ExecuteSql(lsql);
                    writeMakeRunLog(mStrSamCode, "0", "已发出第一次给煤信号");
                }
                else
                {
                    lsql = "update " + mStrZyStatus + " set firdrop=0,secdrop=1";
                    sql.ExecuteSql(lsql);
                    writeMakeRunLog(mStrSamCode, "0", "已发出第二次给煤信号");
                }
            }
            catch (Exception e2)
            {
                tmr_PackageTimer.Enabled = false;
                writeMakeRunLog(mStrSamCode, "2", "发出给煤信号错误");
                return;
            }
            if (mIntPackCnt == 2)
            {
                try
                {
                    lsql = "update " + mStrZyStatus + " set secdrop=0";
                    sql.ExecuteSql(lsql);
                    writeMakeRunLog(mStrSamCode, "0", "第二次给煤信号已复位");

                }
                catch (Exception e2)
                {
                    tmr_PackageTimer.Enabled = false;
                    writeMakeRunLog(mStrSamCode, "2", "发出给煤复位信号错误");
                    return;

                }
            }
            mIntStartTime = DateTime.Now;
            tmr_PackageTimer.Enabled = false;
            tmr_tpfin.Enabled = false;
            tmr_tpfin.Enabled = true;
        }

        private void tmr_BarCode_Tick(object sender, EventArgs e)
        {
            string lsql, lBarCode1, lBarCode2;
            DateTime dt2 = new DateTime();
            TimeSpan ts;
            // MessageBox.Show("开始读取条码");
            mStrCurStep = "tmr_BarCode";//当前的步骤
            //读取条码信息
            lBarCode1 = edit_barCode1.Text;
            lBarCode2 = edit_barCode2.Text;
            //都没有扫到条码
            if (lBarCode1.Equals("") && (lBarCode2.Equals("")))
            {

                dt2 = DateTime.Now;
                ts = dt2 - mIntStartTime;
                label6.Text = ts.TotalMinutes.ToString();
                if (ts.TotalMinutes > 2)
                {
                    writeMakeRunLog(mStrSamCode, "2", "1分钟仍然没有条码信息,报警!!!");
                    tmr_BarCode.Enabled = false;
                    return;

                }
                edit_barCode1.Focus();
                return;
            }
            mstrBarCode = lBarCode1;
            // MessageBox.Show("已读取到条码");
            //  fzj.fzjStart();
            if (mIntPackCnt == 1)
            {
                MessageBox.Show("已发出第一次封装信息");
            }
            else
            {
                MessageBox.Show("已发出第二次封装信号");
            }
            mIntStartTime = DateTime.Now;
            writeMakeRunLog(mStrSamCode, "0", "条码为:" + mstrBarCode + " 已发出封装信号");
            // MessageBox.Show("已发出封装信号 ");
            edit_barCode1.Text = "";
            edit_barCode2.Text = "";

            edit_barCode1.Focus();
            tmr_BarCode.Enabled = false;
            tmr_PackFinish.Enabled = false;
            tmr_PackFinish.Enabled = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string lsql, lerror;
            int count;
            if (mStrSamCode.Equals(""))
            {
                return;
            }
            lsql = "select * from t_Makerunlog where samcode='" + mStrSamCode + "' and handletype in ('2','3')";
            count = oracle.GetRecordCount(lsql);
            if (count > 0)
            {
                MessageBox.Show("请处理报警和信息");
                return;
            }
            if (SysErr())
            {
                MessageBox.Show("处理系统故障");
                tmr_tpfin.Enabled = false;
                return;
            }
            tmr_startMake.Enabled = false;
            tmr_TPTimer.Enabled = false;
            tmr_PackageTimer.Enabled = false;
            tmr_tpfin.Enabled = false;
            tmr_BarCode.Enabled = false;
            tmr_PackFinish.Enabled = false;
            tmr_makeFinish.Enabled = false;
            if (mStrCurStep.Equals("tmr_StartMake"))
            {
                tmr_startMake.Enabled = true;
            }
            else if (mStrCurStep.Equals("tmr_Tp"))
            {
                tmr_TPTimer.Enabled = true;
            }
            else if (mStrCurStep.Equals("tmr_Package"))
            {
                tmr_PackageTimer.Enabled = true;
            }
            else if (mStrCurStep.Equals("tmr_tpFin"))
            {
                tmr_tpfin.Enabled = true;
            }
            else if (mStrCurStep.Equals("tmr_BarCode"))
            {
                mIntStartTime = DateTime.Now;
                tmr_BarCode.Enabled = true;
            }
            else if (mStrCurStep.Equals("tmr_PackFinish"))
            {
                tmr_PackFinish.Enabled = true;

            }
            else if (mStrCurStep.Equals("tmr_makeFinish"))
            {
                tmr_makeFinish.Enabled = true;
            }

        }

        private void tmr_PackFinish_Tick_1(object sender, EventArgs e)
        {
            int iSign;
            string isql, lSystime;
            DateTime dt2;
            int curId, count;
            TimeSpan ts;
            oracleDatabase oracle = new oracleDatabase();

            mStrCurStep = "tmr_packFinish";//当前执行的步骤
            if (fzj.fzjStatus() == true)
            {
                dt2 = DateTime.Now;
                ts = dt2 - mIntStartTime;
                if (ts.TotalMinutes > 5)
                {
                    writeMakeRunLog(mStrSamCode, "2", "5分钟仍然没有封装完成");
                    tmr_PackFinish.Enabled = false;
                    return;
                }
                return;
            }
            //MessageBox.Show("封闭完成，开始保存数据");
            count = oracle.GetRecordCount("select id,samplingCode,samCode from t_sampling where " +
                "samplingCode='" + mstrBarCode + "'");

            if (count == 0)
            {
                lSystime = General.getTime().ToString();
                curId = oracle.getcurid();

                lsql = "insert into t_sampling (id,samplingCode,samCode,samCount,samplingDate,samplingTime,Receiver,samWeight)  " +
          "select " + curId + ",'" + mstrBarCode + "','" + mStrSamCode + "',(select count(id) from t_truckenter where samcode='" + mStrSamCode + "'), " +
              "      '" + General.getDate() + "','" + lSystime + "','无人制样',(select sum(netweight) from t_truckenter where samcode='" + mStrSamCode + "') from dual ";
                oracle.ExecuteSql(lsql);
            }
            if (mIntPackCnt == 1)
            {
                tmr_PackFinish.Enabled = false;
                mIntPackCnt++;
                tmr_PackageTimer.Enabled = false;
                tmr_PackageTimer.Enabled = true;
            }
            else
            {
                MessageBox.Show("第二次封装，数据已保存");
                tmr_PackFinish.Enabled = false;
                tmr_makeFinish.Enabled = false;
                tmr_makeFinish.Enabled = true;
            }
            writeMakeRunLog(mStrSamCode, "0", "封装完成,数据已保存");
        }

        private void fillByToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }

 
      
        


    }
}